package euler.p001_050;

import java.util.HashSet;
import java.util.Set;

import euler.MainEuler;

public class Euler032 extends MainEuler {

    /*
        We shall say that an n-digit number is pandigital
        if it makes use of all the digits 1 to n exactly once;
        for example, the 5-digit number, 15234, is 1 through 5 pandigital.

        The product 7254 is unusual, as the identity, 39 × 186 = 7254,
        containing multiplicand, multiplier, and product is 1 through 9 pandigital.

        Find the sum of all products whose multiplicand/multiplier/product
        identity can be written as a 1 through 9 pandigital.

        HINT: Some products can be obtained in more than one way so be
        sure to only include it once in your sum.
     */
    public String resolve() {
        byte[][] permutaciones = naturalHelper.permutaciones("123456789");

        Set<Integer> set = new HashSet<Integer>();

        for (int i = 0; i < permutaciones.length; i++) {
            for (int j = 1; j <= 9; j++) {
                int a = toIntA(permutaciones[i],j);
                for (int k = j; 2*k <= 9 - j; k++) {
                    int b = toIntB(permutaciones[i],j,k);
                    int c = toIntC(permutaciones[i],j,k);

                    if (!set.contains(c) && (a * b == c)) {
                        set.add(c);
                    }
                }
            }
        }

        permutaciones = null;

        int suma = 0;
        for (Integer i: set) {
            suma+=i;
        }

        return String.valueOf(suma);
        // 45228
    }

    private int toIntC(byte[] bs, int j, int k) {
        int n = 0;
        for (int i = 0; i < bs.length - j - k; i++) {
            n = 10 * n + bs[i + j + k];
        }
        return n;
    }

    private int toIntB(byte[] bs, int j, int k) {
        int n = 0;
        for (int i = 0; i < k; i++) {
            n = 10 * n + bs[i + j];
        }
        return n;
    }

    private int toIntA(byte[] bs, int j) {
        int n = 0;
        for (int i = 0; i < j; i++) {
            n = 10 * n + bs[i];
        }
        return n;
    }

}
